﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.Security;
using Domain.Abstract;
using Domain.Concrete;
using Domain.Entity;
using Pro260Website.Areas.Admin.Models;
using Pro260Website.Infrastructure.Concrete;
using Pro260Website.Models;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.Web.Helpers;

namespace Pro260Website.Controllers
{
    public class AccountController : Controller
    {
        private readonly IAccountRepository _accountRepository;

        public AccountController(IAccountRepository accountRepository)
        {
            this._accountRepository = accountRepository;
        }

        public ViewResult LogOn()
        {
            if(User.Identity.Name.Equals(""))
                return View();
            else
            {
                return View("WelcomeBox");
            }
        }

        [HttpGet]
        public ViewResult CreateUser()
        {
            return View(new CreateUserViewModel());
        }

        [HttpPost]
        public ActionResult CreateUser(CreateUserViewModel model, string returnUrl)
        {

            if (!ReCaptcha.Validate(privateKey: "6Lf14M4SAAAAADVCvhw7f9yv8A5nZIUhB3wkxtCa "))
            {
                    return View("CreateUser");
            }

            if (ModelState.IsValid)
            {
                    MembershipCreateStatus status;
                    Membership.CreateUser(model.Username, model.Password, model.Email,
                                          model.PasswordQuestion, model.PasswordAnswer, true, out status);

                    ViewBag.Message = status.ToString();
                    ModelState.AddModelError("", status.ToString());
                    if (status.Equals(MembershipCreateStatus.Success))
                    {
                        var account = new Account
                                          {
                                              LayoutColor = "coolBlue",
                                              DateOfBirth = model.DateOfBirth,
                                              FirstName = model.FirstName,
                                              LastName = model.LastName,
                                              Username = model.Username,
                                              TwitterName = model.TwitterName
                                          };

                        _accountRepository.SaveAccount(account);

                        if (!Roles.RoleExists("Member"))
                            Roles.CreateRole("Member");
                        Roles.AddUserToRole(model.Username, "Member");
                        FormsAuthentication.SetAuthCookie(model.Username, false);

                        return Redirect(returnUrl ?? Url.Action("Index", "Home"));
                    }
                }

                return View(model);
        }

        [HttpGet]
        public ActionResult ChangeUserInformation()
        {
            if(!User.Identity.Name.Equals(""))
            {
                var accountModel = _accountRepository.FindAccountByUsername(User.Identity.Name);
                var model = new ChangeAccountInfoViewModel
                               {
                                   DateOfBirth = accountModel.DateOfBirth,
                                   Email = Membership.GetUser(User.Identity.Name).Email,
                                   ConfirmEmail = Membership.GetUser(User.Identity.Name).Email,
                                   FirstName = accountModel.FirstName,
                                   LastName = accountModel.LastName,
                                   LayoutColor = accountModel.LayoutColor,
                                   TwitterName = accountModel.TwitterName
                               };
                return View(model);
            }

            return Redirect("/");
        }

        [HttpPost]
        public ActionResult ChangeUserInformation(ChangeAccountInfoViewModel model, string layout)
        {
            if(ModelState.IsValid && !User.Identity.Name.Equals(""))
            {
                Membership.GetUser(User.Identity.Name).Email = model.Email;
                var accountModel = _accountRepository.FindAccountByUsername(User.Identity.Name);

                accountModel.FirstName = model.FirstName;
                accountModel.LastName = model.LastName;
                accountModel.DateOfBirth = model.DateOfBirth.Date;
                accountModel.LayoutColor = layout;
                accountModel.TwitterName = model.TwitterName;
                _accountRepository.SaveAccount(accountModel);

                this.RemoveColorCookie();
                this.AddColorCookie(layout);

                return RedirectToAction("ViewAccount", new {id =accountModel.Username });
            }

            return View(model);
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            if (!User.Identity.Name.Equals(""))
            {
                return View(new ChangePasswordViewModel());
            }

            return RedirectToAction("Index","Home");
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid && !User.Identity.Name.Equals(""))
            {
                if (Membership.ValidateUser(User.Identity.Name, model.OldPassword))
                {
                    Membership.GetUser(User.Identity.Name).ChangePassword(model.OldPassword, model.NewPassword);

                    var accountModel = _accountRepository.FindAccountByUsername(User.Identity.Name);

                    return RedirectToAction("ViewAccount", new {id = accountModel.Username});
                }
                ModelState.AddModelError("", "Old Password does not match current.");
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult ValidateLogOn(LogOnViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Username, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);

                    if (!Membership.GetUser(model.Username).IsLockedOut)
                    {
                        string color = _accountRepository.FindAccountByUsername(model.Username).LayoutColor;

                        this.AddColorCookie(color);

                        return RedirectToAction("Index", "Home");
                    }

                    return LogOut();
                }

                ModelState.AddModelError("", "Incorrect username or password");
                return RedirectToAction("Index", "Home");
            }

            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();

            if (this.HttpContext.Session != null)
                this.HttpContext.Session.Clear();

            this.RemoveColorCookie();

            return RedirectToAction("Index", "Home");
        }

        public ViewResult ViewAccount(string id)
        {
            Account account = _accountRepository.FindAccountByUsername(id);
            return View(account);
        }

        public ViewResult PasswordRecoveryUsername()
        {
            return View();
        }

        [HttpGet]
        public ViewResult PasswordRecoverySecurityQuestion(string username)
        {        
            if(username != null && Membership.GetUser(username) != null)
            {

                return View(Membership.GetUser(username));
            }

            return View("PasswordRecoveryUsername");
        }

        [HttpPost]
        public ActionResult PasswordRecoverySecurityQuestion(string username, string securityQuestion, string securityAnswer)
        {
            MembershipUser user = Membership.GetUser(username);
            try
            {
                user.UnlockUser();
                var password = new TempPassword {Password = user.GetPassword(securityAnswer)};

                //SendPasswordRecoveryEmail(user.Username, securityAnswer);
                return View("Password", password);
            }
            catch (MembershipPasswordException)
            {
            }


            return View("PasswordRecoverySecurityQuestion", user);
        }

        public void SendPasswordRecoveryEmail(string username, string securityAnswer)
        { 
            new EmailProcessor(new EmailSettings(Membership.GetUser(username).Email)).ProcessEmail(Membership.GetUser(username).GetPassword(securityAnswer));
        }

        private void AddColorCookie(string color)
        {
            var c = new HttpCookie("color", color);
            Response.Cookies.Add(c);
        }

        private void RemoveColorCookie()
        {
            if (Request.Cookies["color"] != null)
            {
                var c = new HttpCookie("color") { Expires = DateTime.Now.AddDays(-1) };
                Response.Cookies.Add(c);
            } 
        }
    }

    public class TempPassword
    {
        public string Password { get; set; }
    }



}
